
var hbArr = new Array();
var round = 0;
var level = 0;
var error = 0;
var nums=3;//初始红包数量
function grap() {
	var m = $("#money").html();
	$("#money").html(parseInt(m) + 1);

	clean($(this), true);

}

function clean(obj, grap) {
	if (grap) {
		var i = obj.attr("id");
		obj.off('click');
	} else {
		var i = obj.id;
	}
	//删除之后 整个数组下标变了
	for (var j = 0; j < hbArr.length; j++) {
		if (hbArr[j].id == i) {
			hbArr.splice(j, 1);
		}
	}

	obj.remove();
}

//生成不定数量的红包
function getHongbao() {

	var hb = new Array();
	
	nums = nums > 10 ? 10 : nums;

	var hbObj = $(".jb014").clone();
	for (var i = 0; i < nums; i++) {
		hbArr[i] = hbObj.clone(); //不断成倍复制成新的
		var top = Math.round(Math.random() * 50 + 50) * -1;
		var left = Math.round(Math.random() * 800) + 100;
		hbArr[i].css({
			left : left,
			top : top
		});
		hbArr[i].attr("id", i); //绑定对象
		hbArr[i].id = i;
		hbArr[i]['speed'] = getSpeed(i);
		$(".hbcon").append(hbArr[i]);
	}
	$(".jb014").on('click', grap);
nums++;
}


function start() {

	if (level > 10) {
		clearInterval(interval);
		alert("恭喜你 成功通关!");
		return;
	} else
		if (error > 2) {
		$(".jb014").off('click');
			clearInterval(interval);
			if(confirm("游戏失败!再来一次")){
			  location.reload();
			}else{
			 alert("谢谢你的支持！下次再见！");
			 return;
			}
			return;
		}

	if (hbArr.length < 1) {
		nextGame();
	}

	for (var i = 0; i < hbArr.length; i++) {
		fall(hbArr[i]);
	}

}

function nextGame() {

	if (round < 3 && hbArr.length == 0) {
		var m = $("#level").html();
		$("#level").html(level + 1);
		level++;
		round = 0;
		getHongbao();
	}
}

function setScore(){
var scores=$("#money").html();
$.post("/index.php?plane/score",{score:scores},function(data){
					  if(data.status==false){
					  alert(data.message);
					  }
					  },"json");

}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

//每个红包掉落的速度不一致的 等级越高，越来越多的红包越快
function getSpeed(i) {

	if (i <= (nums -level)) {
		return Math.round(Math.random() * 8) + 10; //5~15
	} else {
		return Math.round(Math.random() * level * 8) + 10; //速度变快
	}
}

function fall(jb) {

	var direct;
	var left = jb.position().left;
	var top = jb.position().top;
	var speed = jb.speed;

	if (top > 400 || hbArr.length == 0) {

		//不动了
		round++;
		error++;
		clean(jb, false);
		nextGame();
		return;
	}
	direct = Math.round(Math.random() * 1);
	if (left < 40) {
		direct = 0;
	} else if (left > 850) {
		direct = 1;
	}
	if (direct > 0) {
		left = left - speed + "px";
	} else {
		left = left + speed + "px";
	}

	top = top + speed;
	jb.css({
		"top" : top,
		"left" : left
	});
}
